package com.jic.member.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.member.entity.DisCommissionConf;
import com.jic.member.entity.DisCommissionInfo;
import com.jic.member.entity.MememberUser;
import com.jic.member.mapper.DisCommissionConfMapper;
import com.jic.member.mapper.DisCommissionInfoMapper;
import com.jic.member.mapper.MememberUserMapper;
import com.jic.member.request.DistributionRestRequest;
import com.jic.member.response.DistributionOrderRestResponse;
import com.jic.member.service.DisCommissionInfoService;
import com.jic.order.api.DistributionOrderApi;
import com.jic.order.request.DistributorOrderRequest;
import com.jic.order.response.OrderGoodsInfo;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.math.BigDecimal.ROUND_DOWN;

/**
 * 佣金明细
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-09-15 11:56:08
 */
@Service
public class DisCommissionInfoServiceImpl implements DisCommissionInfoService {

    @Autowired
    private DisCommissionInfoMapper disCommissionInfoMapper;

    @Autowired
    private DisCommissionConfMapper disCommissionConfMapper;

    @Resource
    private MememberUserMapper mememberUserMapper;

    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Resource
    private DistributionOrderApi distributionOrderApi;

    @Override
    public long insert(DisCommissionInfo commissionInfo) {
        long flag = disCommissionInfoMapper.insert(commissionInfo);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return disCommissionInfoMapper.delete(id);
    }

    @Override
    public long update(DisCommissionInfo commissionInfo) {
        return disCommissionInfoMapper.update(commissionInfo);
    }

    @Override
    public DisCommissionInfo queryByPrimaryKey(Long id) {
        return disCommissionInfoMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<DisCommissionInfo> query(DisCommissionInfo commissionInfo) {
        return disCommissionInfoMapper.query(commissionInfo);
    }

    @Override
    public PageResult<DisCommissionInfo> queryPage(DisCommissionInfo commissionInfo, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<DisCommissionInfo> list = disCommissionInfoMapper.queryPage(startIndex, pageQuery.getLimit(), commissionInfo);
        long count = disCommissionInfoMapper.queryPageCount(commissionInfo);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    @Override
    public BigDecimal getCommissionCount(DisCommissionInfo commissionInfo) {

        RestResult<PageResult<DistributionOrderRestResponse>> pageResultRestResult = this.getDistributionOrderListPage(new DistributionRestRequest() {{
            setStart(1);
            setLimit(1000);
            setToken(commissionInfo.getToken());
        }});
        //分销总额
        final BigDecimal[] totalAmountOfDistribution = {BigDecimal.ZERO};
        //查询总价
        if (RestResult.checkIsSuccess(pageResultRestResult)) {
            List<DistributionOrderRestResponse> distributionOrderRestResponses = pageResultRestResult.getData().getRows();
            if (CollectionUtils.isNotEmpty(distributionOrderRestResponses)) {
                distributionOrderRestResponses.forEach(distributionOrderRestResponse -> {
                    totalAmountOfDistribution[0] = totalAmountOfDistribution[0].add(distributionOrderRestResponse.getCommission());
                });
            }
        }
        return totalAmountOfDistribution[0];
    }

    @Override
    public RestResult<PageResult<DistributionOrderRestResponse>> getDistributionOrderListPage(DistributionRestRequest request) {
        //查询当前登录人
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        //查询下级
        List<MememberUser> mememberUserList = mememberUserMapper.query(new MememberUser() {{
            setAllocationPid(member.getId());
        }});
        List<Long> memberIds = mememberUserList.stream().map(MememberUser::getId).collect(Collectors.toList());

        DistributorOrderRequest distributorOrderRequest = new DistributorOrderRequest();
        distributorOrderRequest.setBuyerId(memberIds);
        distributorOrderRequest.setDistributionId(member.getId());
        distributorOrderRequest.setLimit(request.getLimit());
        distributorOrderRequest.setStart(request.getStart());
        PageResult<OrderGoodsInfo> orderGoodsInfoPageResult = distributionOrderApi.queryDistributionOrder(distributorOrderRequest);

        //查询分销佣金比例
        List<DisCommissionConf> commissionResponseList = disCommissionConfMapper.listPageBySelective(new DisCommissionConf());
        List<DistributionOrderRestResponse> distributionOrderRestResponseList = orderGoodsInfoPageResult.getRows().stream().map(temp -> {
            DistributionOrderRestResponse distributionOrderRestResponse = new DistributionOrderRestResponse();
            if (temp.getDistributionType() == 1) {
                if (CollectionUtils.isNotEmpty(commissionResponseList)) {
                    Optional<DisCommissionConf> cartOptional = commissionResponseList.stream().filter(item1 ->
                            item1.getCommissionType() == 1).findFirst();
                    if (cartOptional.isPresent()) {
                        BigDecimal rate = cartOptional.get().getCommissionRate().divide(new BigDecimal(100));
                        distributionOrderRestResponse.setCommission(temp.getSaleTotalAmount().multiply(rate));
                    } else {
                        distributionOrderRestResponse.setCommission(BigDecimal.ZERO);
                    }
                } else {
                    distributionOrderRestResponse.setCommission(BigDecimal.ZERO);
                }
            } else {
                if (CollectionUtils.isNotEmpty(commissionResponseList)) {
                    Optional<DisCommissionConf> cartOptional = commissionResponseList.stream().filter(item1 ->
                            item1.getCommissionType() == 4).findFirst();
                    if (cartOptional.isPresent()) {
                        BigDecimal rate = cartOptional.get().getCommissionRate().divide(new BigDecimal(100));
                        distributionOrderRestResponse.setCommission(temp.getSaleTotalAmount().multiply(rate));
                    } else {
                        distributionOrderRestResponse.setCommission(BigDecimal.ZERO);
                    }
                } else {
                    distributionOrderRestResponse.setCommission(BigDecimal.ZERO);
                }
            }
            distributionOrderRestResponse.setOrderNo(temp.getOrderNo());
            distributionOrderRestResponse.setStatus(temp.getOrderStatus());
            distributionOrderRestResponse.setCreateTime(temp.getCreateTime());
            OrderGoodsInfo orderGoodsInfo = distributionOrderApi.getDistributionOrderInfo(temp.getOrderNo());
            if (null != orderGoodsInfo) {
                distributionOrderRestResponse.setActualPayTotalAmount(orderGoodsInfo.getSaleUnitPrice());
                distributionOrderRestResponse.setGoodsName(orderGoodsInfo.getGoodsName());
                MememberUser mememberUser = mememberUserMapper.queryByPrimaryKey(orderGoodsInfo.getBuyerId());
                if (mememberUser != null) {
                    distributionOrderRestResponse.setBuyName(mememberUser.getName());
                    distributionOrderRestResponse.setMemberName(mememberUser.getNickName());
                }
            }
            return distributionOrderRestResponse;
        }).filter(item -> item != null).collect(Collectors.toList());
        PageResult<DistributionOrderRestResponse> pageResult = new PageResult<>();
        pageResult.setRows(distributionOrderRestResponseList);
        pageResult.setTotal(orderGoodsInfoPageResult.getTotal());
        return RestResult.success(pageResult);
    }
}
